package net.bbtang.website.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import net.bbtang.website.mapper.AchievementMapper;
import net.bbtang.website.mapper.UserAccountMapper;
import net.bbtang.website.mapper.UserMapper;
import net.bbtang.website.pojo.UserDTO;
import net.bbtang.website.pojo.UserSignInfoDTO;
import net.bbtang.website.service.UserInfoService;
import net.bbtang.website.service.UserStatisticsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;




@Service("userStatisticsService")
public class UserStatisticsServiceImpl implements UserStatisticsService {
	
	
	@Autowired
	AchievementMapper achievementMapper;

	@Override
	public UserSignInfoDTO getStatistics(Integer userId) {
		//查询统计信息
		UserSignInfoDTO userStatistics = achievementMapper.getSignStatistics(userId);
		if(userStatistics != null){
			//更新
			//判断最后签到时间的下一天是否等于当天，是：+1，否：清0
			String nextDay = getNextDay(userStatistics.getEndSignDay());
			if(nextDay.equals(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()).toString())){
				userStatistics.setSignCountDay(userStatistics.getSignCountDay()+1);
			}else{
				userStatistics.setSignCountDay(0);
			}
			achievementMapper.updateSignStatistics(userStatistics);
		}else{
			userStatistics = new UserSignInfoDTO();
			userStatistics.setUserId(userId);
			userStatistics.setSignCountDay(1);
			userStatistics.setEndSignDay(new Date());
			//新增
			achievementMapper.addSignStatistics(userStatistics);
		}
		
		return userStatistics;
	}

	public static String getNextDay(Date date) {  
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(date);  
        calendar.add(Calendar.DAY_OF_MONTH, -1);  
        date = calendar.getTime();  
        return new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(date).toString();  
    }  
	


}
